<template>
  <div class="param-setting-wrapper">
    <el-row :gutter="20" style="height: 100%;">
      <el-col :span="5" style="height: 100%;">
        <el-form :inline="true" :model="formInline">
          <el-form-item label="服务描述">
            <el-select v-model="formInline.applicationLike" placeholder="请选择服务描述" @change="changeAppItem">
              <el-option
               v-for="(item) in dockerListOpt"
               :key="item.appDeployName"
               :label="item.appName"
               :value="item.appDeployName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-scrollbar class="tree-scrollbar">
          <keep-alive>
            <CustomTree :treeData="treeData" :curNodeKey="nodeId" @nodeClick="handleClick" ref="customTree"></CustomTree>
          </keep-alive>
        </el-scrollbar>
      </el-col>
      <el-col :span="19" style="height: 100%;">
        <el-form :inline="true" :model="formInline">
          <el-form-item label="配置名称">
            <el-input v-model="formInline.qryWord" placeholder="请输入配置名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchOrg">搜索</el-button>
            <!-- <el-button type="primary" @click="refreshConf">更新配置</el-button> -->
            <el-button type="primary" @click="popNewAddDialog">新增配置</el-button>
          </el-form-item>
        </el-form>
        <!-- 表格 开始 -->
        <el-table :data="tableData" v-loading="loading" :height="tableHeight" stripe>
          <el-table-column width="20"></el-table-column>
          <el-table-column label="序号" width="60">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="配置名称" prop="name"></el-table-column>
          <el-table-column label="配置键" prop="key" v-if="nodeId!=='-1'"></el-table-column>
          <el-table-column label="配置值" prop="value" v-if="nodeId!=='-1'"></el-table-column>
          <el-table-column label="备注" prop="remark" v-if="nodeId!=='-1'"></el-table-column>
          <el-table-column label="更新时间" prop="updateTime" v-if="nodeId!=='-1'"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.id)">编辑</el-link>&nbsp;
              <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.id)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格 结束 -->
      </el-col>
    </el-row>

    <!-- 对话框 开始 -->
    <el-dialog title="配置" :visible.sync="dialogFormVisible" width="660px" @closed="closeDialog">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog">
        <el-form-item label="配置键" label-width="110px" prop="key" v-if="nodeId!=='-1'">
          <el-input v-model="dialogForm.key" placeholder="请输入配置键" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="配置值" label-width="110px" prop="value" v-if="nodeId!=='-1'">
          <el-input v-model="dialogForm.value" placeholder="请输入配置值" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="配置名称" label-width="110px" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入配置名称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="开发环境" label-width="110px" prop="profile" v-if="nodeId!=='-1'">
          <el-select v-model="dialogForm.profile" placeholder="请选择开发环境">
            <el-option label="正式环境" value="prod"></el-option>
            <el-option label="开发环境" value="dev"></el-option>
            <el-option label="测试环境" value="test"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" label-width="110px" prop="label" v-if="nodeId!=='-1'">
          <el-input v-model="dialogForm.label" placeholder="请输入版本号" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="110px" prop="remark" v-if="nodeId!=='-1'">
          <el-input v-model="dialogForm.remark" placeholder="请输入备注" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import {
  getDockerAppList,
  getConfigwebList,
  configwebAdd,
  updateConfigweb,
  deleteConfigweb
} from '@/api/systemManage'
import { deepClone } from '@/utils'
import CustomTree from './CustomTree'
export default {
  name: 'ParamSetting',
  data () {
    return {
      formInline: {
        applicationLike: '',
        qryWord: ''
      },
      dockerListOpt: [],
      listData: [],
      treeData: [],
      tableHeight: window.innerHeight - 300,
      loading: false,
      dialogFormVisible: false,
      dialogForm: {
        key: '',
        value: '',
        name: '',
        profile: '',
        label: '',
        remark: ''
      },
      dialogMode: '',
      rules: {
        key: [{ required: true, message: '请输入配置键', trigger: 'blur' }],
        value: [{ required: true, message: '请输入配置值', trigger: 'blur' }],
        name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
        profile: [{ required: true, message: '请选择开发环境', trigger: 'change' }],
        label: [{ required: true, message: '请输入版本号', trigger: 'blur' }]
      },
      nodeId: '-1', // 当前选中节点的id
      curId: ''// 当前要编辑的id
    }
  },
  computed: {
    tableData () {
      let tbData = this.listData.filter((item) => {
        return item.parentId === this.nodeId
      })
      if (tbData.length === 0) {
        return this.listData.filter((item) => {
          return item.id === this.nodeId
        })
      } else {
        return tbData
      }
    }
  },
  components: {
    CustomTree
  },
  methods: {
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter((item) => {
        return item.appDeployName === code
      })
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].appName
    },
    getDockerListAndShow () {
      getDockerAppList({
        page: 1,
        pageSize: 10000
      }).then((res) => {
        this.dockerListOpt = res.data.queryResult
        this.dockerListOpt.unshift({
          appDeployName: 'system',
          appName: '默认配置'
        })
        this.$set(this.formInline, 'applicationLike', this.dockerListOpt[0].appDeployName)
        this.getConfListShow()
      })
    },
    getConfListShow (qryType) {
      getConfigwebList({
        applicationLike: this.formInline.applicationLike,
        qryWord: this.formInline.qryWord,
        pageSize: 100000
      }).then((res) => {
        if (!qryType) {
          this.listData = res.data.queryResult
          this.$set(this.treeData, 0, { name: this.convertKeyToVal(this.formInline.applicationLike, this.dockerListOpt), children: [], id: '-1' })
          this.$set(this.treeData[0], 'children', this.toTreeData(res.data.queryResult))
          console.log(this.treeData)
        } else {
          let resultList = deepClone(res.data.queryResult)
          let parentIdlist = [...new Set(res.data.queryResult.map(item => item.parentId))]
          // 遍历查找父节点
          if (this.formInline.qryWord !== '' && this.formInline.qryWord !== undefined) {
            this.listData.forEach(parent => {
              parentIdlist.forEach(item => {
                if (!this.inArrayId(resultList, item) && item === parent.id) {
                  resultList.push(parent)
                }
              })
            })
          }
          this.listData = resultList
          this.$set(this.treeData[0], 'children', this.toTreeData(resultList))
          this.nodeId = '-1'
        }
      })
    },
    inArrayId (arr, value) {
      for (let i = 0; i < arr.length; i++) {
        if (value === arr[i].id) {
          return true
        }
      }
      return false
    },
    searchOrg () {
      this.getConfListShow('search')
    },
    refreshConf () {
    },
    changeAppItem () {
      this.$set(this.formInline, 'qryWord', '')
      this.nodeId = '-1'
      this.getConfListShow()
    },
    toTreeData (arr = []) {
      let tempArr = deepClone(arr)
      // 把每一项id作为key，该对象作为value组成一个新对象
      let obj = {}
      tempArr.forEach((item) => {
        obj[item.id] = item
      })

      let result = []
      tempArr.forEach((item) => {
        let parent = obj[item.parentId]
        if (parent) {
          (parent.children || (parent.children = [])).push(item)
        } else {
          result.push(item)
        }
      })

      return result
    },
    handleClick (data, node, self) {
      console.log(data, node)
      this.nodeId = data.id
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    showToDialog (id) {
      let res = this.listData.filter(item => item.id === id)
      let data = res.length === 0 ? {} : res[0]
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.dialogForm[key] = data[key]
        }
      }
    },
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // -----------------
          let requestData = deepClone(this.dialogForm)
          requestData.application = this.formInline.applicationLike
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            requestData.parentId = this.nodeId
            configwebAdd(requestData).then((res) => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.getConfListShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.id = this.curId
            updateConfigweb(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getConfListShow()
              this.dialogFormVisible = false
            })
          }
          // -----------------
        } else {
          return false
        }
      })
    },
    editDetail (id) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = id
      this.showToDialog(id)
    },
    deleteDetail (id) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteConfigweb({ id }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getConfListShow()
        })
      })
    },
    closeDialog () {
      this.dialogMode = ''
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
    }
  },
  created () {
  },
  mounted () {
    this.getDockerListAndShow()
  }
}
</script>

<style lang="scss" scoped>
.param-setting-wrapper {
  height: calc(100vh - 200px);
  min-height: 500px;
  background-color: #ffffff;
  padding: 15px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  border-radius: 3px;
  .add-btn {
    margin-bottom: 10px;
  }
  .tree-scrollbar {
    height: calc(100% - 100px);
  }
  .btn-inline {
    margin-bottom: 14px;
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
<style lang="scss">
.param-setting-wrapper {
  .el-table {
    .el-table__header-wrapper {
      .el-table__header {
        background-color: #f2f5f7;
      }
    }
  }
}
</style>
